<script lang="ts" setup>
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useThemeStore } from '@/store'
import type { Theme } from '@/store/modules/theme'
import { usePageId } from '@/hooks/usePageId'
import { useRoute, useRouter } from 'vue-router'
import AddBar from './components/AddBar/index.vue'
import { useTodoListStore } from '@/stores/list.store'
import ListItem from './components/ListItem/index.vue'
import { useNotification } from '@/hooks/useNotification'
import SettingBtn from './components/SettingBtn/index.vue'
import DetailEditor from './components/DetailEditor/index.vue'
import { type IListItem, PageId } from '@/stores/interfaces/list.interface'

const route = useRoute()
const router = useRouter()

const themeStore = useThemeStore()

const ThemeConfig = ref<Theme | null>()

/** @desc 无任务时随机一言 */
const words = ref<string>('')
const getWords = async () => {
  // const data = await fetch('https://api.mcloc.cn/words/')
  // words.value = await data.text()
  words.value = '暂无任务'
}

const { pageId } = usePageId()
const todoListStore = useTodoListStore()
function getTodoList() {
  todoListStore.getList(pageId.value)
}

/** @desc 获取主题与todo列表 */
const getThemeAndList = () => {
  if (['/user', '/about'].includes(route.path)) return
  ThemeConfig.value = themeStore.getTheme(route.params)
  if (ThemeConfig.value === null) router.push('/error')
  getTodoList()
}

const editorState = ref<{
  listItem: IListItem
  visible: boolean
  changed: boolean
}>({
  listItem: {
    owner: '',
    worker: '',
    title: '',
    type: pageId.value,
    distribution: '',
    id: 'null',
    finished: false,
    important: false,
    createdBy: '',
    createdAt: 0
  },
  visible: false,
  changed: false
})
function handleDetail(listInfo: IListItem) {
  editorState.value = {
    listItem: listInfo,
    visible: true,
    changed: false
  }
}
const { Notification } = useNotification()
const { t } = useI18n()
function handleCloseDrawer() {
  editorState.value.visible = false
  if (!editorState.value.changed) return
  if (pageId.value === PageId.distribution) {
    todoListStore.getList(pageId.value)
    return Notification.error(t('list.auth.error'))
  }
  todoListStore.updateList(editorState.value.listItem)
}
function handleUpdate(newList: IListItem) {
  editorState.value.changed = true
  editorState.value.listItem = newList
}

const getSvgPath = () => `/plants/${~~(Math.random() * 5)}.svg`

const listAnimation = ref<'list-box' | undefined>()
/** @desc 列表入场动画 */
function animation() {
  listAnimation.value = 'list-box'
  setTimeout(() => {
    listAnimation.value = undefined
  }, 700)
}
/** @desc 初始化页面数据 */
watch(
  () => route.params,
  () => {
    animation()
    getThemeAndList()
    if (todoListStore.todoList?.[pageId.value]?.length ?? 0 === 0) getWords()
  },
  {
    immediate: true
  }
)
</script>

<template>
  <SettingBtn />
  <div :class="`list-block ${ThemeConfig?.backgroundImage || 'null'}`">
    <div class="p-8 text-light-50">
      <p class="mb-2 text-3xl font-bold">
        <span>
          {{
            (ThemeConfig?.uuid || 0) < 8
              ? $t(ThemeConfig?.title || 'list.error')
              : ThemeConfig?.title
          }}
        </span>
      </p>
      <time class="text-sm">{{
        ThemeConfig?.subtitle ? new Date().toLocaleDateString() : ''
      }}</time>
    </div>
    <section class="scrollbar mx-8 mb-2 flex-1 overflow-x-auto">
      <ul :class="listAnimation">
        <TransitionGroup name="list">
          <li v-for="listItem of todoListStore.todoList[pageId]" :key="listItem.id">
            <ListItem :item-info="listItem" @handle-detail="handleDetail(listItem)" />
          </li>
        </TransitionGroup>
      </ul>
      <a-empty v-if="todoListStore.todoList?.[pageId]?.length === 0">
        <template #image>
          <img :src="getSvgPath()" class="w-full !h-96" />
        </template>
        <span class="relative text-slate-900 -top-15 dark:text-light-200">
          {{ words }}
        </span>
      </a-empty>
    </section>
    <div>
      <AddBar v-show="pageId !== PageId.distribution" :page-id="pageId" />
    </div>
  </div>
  <a-drawer
    width="300px"
    :closable="false"
    :footer="false"
    :title="editorState.listItem.title"
    :visible="editorState.visible"
    :unmount-on-close="true"
    @cancel="handleCloseDrawer"
  >
    <Suspense>
      <DetailEditor :list-item="editorState.listItem" @update:list-item="handleUpdate" />
    </Suspense>
  </a-drawer>
</template>

<style scoped>
.list-block {
  transition: background-color 0.3s ease;
  background-color: v-bind('ThemeConfig?.background');

  @apply bg-cover rounded-tl-xl flex flex-col min-h-full max-h-full;
  @apply dark:bg-dark-700;
}

@media (max-width: 768px) {
  .list-block {
    @apply rounded-none;
  }
}

@keyframes list-box-enter {
  from {
    opacity: 0;
    transform: translateY(30px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.list-enter-from,
.list-leave-to {
  opacity: 0;
  transform: translateX(90px);
}

.list-move,
.list-enter-active,
.list-leave-active {
  transition: all 0.5s;
}

.list-leave-active {
  @apply w-full absolute;
}

.scrollbar::-webkit-scrollbar {
  width: 0;
}
</style>
